package com.easemob.helpdesk.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.easemob.helpdesk.AppConfig;
import com.easemob.helpdesk.listener.OnDataItemClickListener;
import com.easemob.helpdesk.utils.PreferenceUtils;
import com.housekeeperapp.R;
import com.easemob.helpdesk.adapter.WaitAccessAdapter;
import com.easemob.helpdesk.widget.recyclerview.DividerLine;
import com.hyphenate.kefusdk.entity.user.HDVisitorUser;
import com.hyphenate.kefusdk.gsonmodel.main.WaitQueueResponse;
import com.jude.easyrecyclerview.EasyRecyclerView;

import java.util.ArrayList;
import java.util.List;

import static com.easemob.helpdesk.fragment.WaitAccessFragment.REQUEST_CODE_PREVIEW_WAITTING_SESSION;
import static com.easemob.helpdesk.fragment.WaitAccessFragment.REQUEST_CODE_ALERT_DIALOG_CLOSE;
import static com.easemob.helpdesk.fragment.WaitAccessFragment.REQUEST_CODE_ALERT_DIALOG_TRANSFER;

import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 待接入的搜索界面
 * <p/>
 * Created by on 16/3/15.
 */
public class SearchWaitAccessActivity extends BaseActivityV2 {

    private static final String TAG = SearchWaitAccessActivity.class.getSimpleName();
    /**
     * 进入提示框的REQUEST_CODE
     */
    private static final int REQUEST_CODE_ALERT_DIALOG = 0x01;

    /**
     * 列表View（此处为EasyRecyclerView）
     */
    private EasyRecyclerView recyclerView;
    /**
     * 搜索清空，结束按钮
     */
    private ImageButton btnClear;
    /**
     * 搜索的文本框
     */
    private EditText query;

    private RelativeLayout rl_back;
    /**
     * 列表填充的具体数据
     */
    private List<WaitQueueResponse.ItemsBean> mList = new ArrayList<WaitQueueResponse.ItemsBean>();
    /**
     * 填充数据的适配器
     */
    private WaitAccessAdapter mAdapter;
    private WaitQueueResponse.ItemsBean mSelectSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppConfig.setFitWindowMode(this);
        setContentView(R.layout.activity_search_history_session);
        initView();
        List<WaitQueueResponse.ItemsBean> list = (List<WaitQueueResponse.ItemsBean>) getIntent().getSerializableExtra("list");
        if (list != null && list.size() > 0) {
            mList.addAll(list);
        }
        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        //设置分割线
        DividerLine dividerLine = new DividerLine(DividerLine.VERTICAL);
        dividerLine.setSize(1);
        dividerLine.setColor(0xFFDDDDDD);
        recyclerView.addItemDecoration(dividerLine);

//        recyclerView.setEmptyView();

        recyclerView.setAdapterWithProgress(mAdapter = new WaitAccessAdapter(this));
//        mAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                clickAccess(position, 1);
//            }
//        });

        mAdapter.setOnDataItemClickListener(new OnDataItemClickListener<WaitQueueResponse.ItemsBean>() {
            @Override
            public void onClick(View view, WaitQueueResponse.ItemsBean data) {
                boolean isOpenPreviewSession = PreferenceUtils.getInstance().getOpenPreviewMsgStatus();
                if (isOpenPreviewSession){
                    previewSession(data);
                }else {
                    receptionSession(data);
                }

            }
        });

        mAdapter.addAll(mList);
        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    btnClear.setVisibility(View.VISIBLE);
                } else {
                    btnClear.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mAdapter.clear();
                mAdapter.addAll(filter(mList, editable.toString()));
            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                query.getText().clear();
                finish();
            }
        });

        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void previewSession(WaitQueueResponse.ItemsBean data){
        mSelectSession = data;
        String sessionId = data.getSessionId();

        HDVisitorUser toUser = new HDVisitorUser();
        toUser.setUserId(data.getVisitorId());
        toUser.setUsername(data.getVisitorName());
        toUser.setNicename(data.getVisitorName());
        Intent intent = new Intent();
        intent.setClass(SearchWaitAccessActivity.this, PreviewWaitingSessionDialog.class);
        intent.putExtra("user", toUser);
        intent.putExtra("visitorid", sessionId);
        intent.putExtra("originType", data.getOriginType());
        intent.putExtra("techChannelName", data.getChanneName());
        startActivityForResult(intent, REQUEST_CODE_PREVIEW_WAITTING_SESSION);
    }

    //询问直接接入
    private void receptionSession(WaitQueueResponse.ItemsBean data){
        mSelectSession = data;
        Intent intent = new Intent(this, AlertDialog.class);
        intent.putExtra("position", 1);
        intent.putExtra("msg", "您确认要接待此会话吗？");
        intent.putExtra("okString", "确认");
        startActivityForResult(intent, REQUEST_CODE_PREVIEW_WAITTING_SESSION);
    }

//    public void clickAccess(int position, int index){
//        if (index == 1){
//            Intent intent = new Intent(this, AlertDialog.class);
//            intent.putExtra("position", position);
//            intent.putExtra("msg", "您确认要接待此会话吗？");
//            intent.putExtra("okString", "确认");
//            startActivityForResult(intent, REQUEST_CODE_PREVIEW_WAITTING_SESSION);
//        }else if (index == 2){
//            startActivityForResult(new Intent(this, TransferActivity.class).putExtra("position", position), REQUEST_CODE_ALERT_DIALOG_TRANSFER);
//        }else if (index == 3){
//            //waitAbort
//            Intent intent = new Intent(this, AlertDialog.class);
//            intent.putExtra("position", position);
//            intent.putExtra("msg", "您确认要关闭此会话吗？");
//            intent.putExtra("okString", "确认");
//            startActivityForResult(intent, REQUEST_CODE_ALERT_DIALOG_CLOSE);
//        }
//
//    }



    /**
     * 页面从栈中返回到第一个时，触发的回调
     *
     * @param requestCode 请求码
     * @param resultCode  结束码
     * @param data        Intent数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if(requestCode == REQUEST_CODE_PREVIEW_WAITTING_SESSION){
//                final int position = data.getIntExtra("position", -1);
//                if (position == -1){
//                    return;
//                }
//                WaitQueueResponse.ItemsBean entity = mAdapter.getItem(position);
                boolean isTransfer = data.getBooleanExtra("isTransfer", false);

                data.putExtra("entty", mSelectSession);
                data.putExtra("isTransfer",isTransfer);
                if (isTransfer){
                    data.putExtra("userId",data.getStringExtra("userId"));
                }
                setResult(RESULT_OK,data);
                finish();
            }
//            else if(requestCode == REQUEST_CODE_ALERT_DIALOG_TRANSFER){
//                final int position = data.getIntExtra("position", -1);
//                String userId = data.getStringExtra("userId");
//                long queueId = data.getLongExtra("queueId", 0);
//                if (position == -1){
//                    return;
//                }
//                WaitQueueResponse.ItemsBean entity = mAdapter.getItem(position);
//                setResult(RESULT_OK, new Intent().putExtra("entty", entity).putExtra("index", 2).putExtra("userId", userId).putExtra("queueId",queueId));
//                finish();
//            }
//            else if(requestCode == REQUEST_CODE_ALERT_DIALOG_CLOSE){
//                final int position = data.getIntExtra("position", -1);
//                if (position == -1){
//                    return;
//                }
//                WaitQueueResponse.ItemsBean entity = mAdapter.getItem(position);
//                setResult(RESULT_OK, new Intent().putExtra("entty", entity).putExtra("index", 3));
//                finish();
//            }
//            if (requestCode == REQUEST_CODE_ALERT_DIALOG) {
//                final int position = data.getIntExtra("position", -1);
//                if (position == -1) {
//                    return;
//                }
//
//            }
        }
    }

    /**
     * 初始化View控件
     */
    private void initView() {
        recyclerView = (EasyRecyclerView)this.findViewById(R.id.recyclerView);
        btnClear = (ImageButton)this.findViewById(R.id.search_clear);
        rl_back = (RelativeLayout) this.findViewById(R.id.rl_back);
        query = (EditText)this.findViewById(R.id.query);
        query.setHint("请输入姓名");
    }

    /**
     * 数据的筛选方法：
     * 根据输入的文本内容模糊筛选
     *
     * @param models 当前所有数据
     * @param query  输入的文本内容
     * @return 筛选后的符合条件的数据
     */
    private List<WaitQueueResponse.ItemsBean> filter(List<WaitQueueResponse.ItemsBean> models, String query) {
        query = query.toLowerCase();
        final List<WaitQueueResponse.ItemsBean> filteredModelList = new ArrayList<WaitQueueResponse.ItemsBean>();
        for (WaitQueueResponse.ItemsBean model : models) {
            final String text = model.getVisitorName();
            if (!TextUtils.isEmpty(text)&&text.contains(query)) {
                filteredModelList.add(model);
            }
        }
        return filteredModelList;
    }

}
